package com.wlyuan.open.domain.source.dispatcher.conversion;

import com.wlyuan.core.exception.AssertUtils;
import com.wlyuan.core.exception.ValueError;
import com.wlyuan.open.constants.CarrierTypeEnum;
import com.wlyuan.open.dto.OpenRelationSyncDTO;
import com.wlyuan.open.utils.LongUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.stereotype.Service;

/**
 * @author lijing
 * @description
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class OpenDispatcherRelationConversion implements OpenDispatcherConversion<OpenRelationSyncDTO> {
    private final BaseOpenDispatcherConversion baseOpenDispatcherConversion;

    @Override
    public void convert(OpenRelationSyncDTO source) {
        //上游承运方租户
        var tenant = source.getTenantId();
        if (LongUtils.notNullLong(tenant)) {
            var tenantId = baseOpenDispatcherConversion.tenant(tenant);
            AssertUtils.assertNotNull(tenantId, new ValueError("OpenRelationSyncDTO上游租户不存在:" + tenant), source);
            source.setTenantId(tenantId);
            source.setUpstream(tenantId);
        }
        //承运方id
        var carrierId = source.getCarrierId();
        if (LongUtils.notNullLong(carrierId)) {
            var carrier = baseOpenDispatcherConversion.carrier(carrierId, CarrierTypeEnum.ONLINE.getValue(), source.getUpstream());
            AssertUtils.assertNotNull(carrier, new ValueError("OpenRelationSyncDTO上游承运方不存在:" + carrierId + ",上游租户：" + source.getUpstream()), source);
            source.setCarrierId(carrier.getCarrierId());
        }
        //客户租户
        var downTenant = source.getDownstream();
        if (LongUtils.notNullLong(downTenant)) {
            var tenantId = baseOpenDispatcherConversion.tenant(downTenant);
            AssertUtils.assertNotNull(tenantId, new ValueError("OpenRelationSyncDTO下游客户租户不存在：" + downTenant), source);
            source.setDownstream(tenantId);
        }
        //客户id
        var customerId = source.getCustomerId();
        if (LongUtils.notNullLong(customerId)) {
            var customer = baseOpenDispatcherConversion.customer(customerId, source.getCustomerType(), source.getDownstream());
            AssertUtils.assertNotNull(customer, new ValueError("OpenRelationSyncDTO下游客户不存在：" + customerId + ",下游租户：" + source.getDownstream()), source);
            source.setCustomerId(customer.getCustomerId());
        }
        //创建人
        var createBy = source.getCreateBy();
        if (LongUtils.notNullLong(createBy)) {
            Long user = baseOpenDispatcherConversion.user(createBy);
            AssertUtils.assertNotNull(user, new ValueError("OpenRelationSyncDTO创建人不存在:" + createBy), source);
            source.setCreateBy(user);
        }

    }
}
